package com.tencent.qf.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tencent.qf.user.dto.MidApiJsSdkInfo;
import com.tencent.qf.common.gateway.midapi.MidApiConfig;
import com.tencent.qf.common.gateway.midapi.MidApiUtils;
import com.tencent.qf.common.gateway.midapi.dto.MidApiResponse;
import com.tencent.qf.user.dto.MidApiUserInfo;
import com.tencent.qf.user.dto.request.MidApiGetJsSdkRequest;
import com.tencent.qf.user.dto.request.MidApiGetUserByUnionidRequest;
import com.tencent.qf.user.service.MidApiUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Slf4j
@Service
public class MidApiUserServiceImpl implements MidApiUserService {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private MidApiConfig midApiConfig;
    /**
     * 根据unionId获取用户信息
     *
     * @param request
     * @return
     */
    @Override
    public MidApiUserInfo getByUnionid(MidApiGetUserByUnionidRequest request) {
        MidApiUtils.sign(request, midApiConfig.getAppKey(), midApiConfig.getAppSecret());
        log.info("请求MidApi获取用户信息：/oapi/user/getbyunionid 入参{}", JSON.toJSONString(request));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(midApiConfig.getUrl() + "/oapi/user/getbyunionid", request, String.class);
        log.info("请求MidApi获取用户信息：/oapi/user/getbyunionid 出参{}", JSON.toJSONString(responseEntity));
        if(responseEntity.getStatusCode() == HttpStatus.OK){
            String body = responseEntity.getBody();
            MidApiResponse<MidApiUserInfo> midApiResponse = JSON.parseObject(body, new TypeReference<MidApiResponse<MidApiUserInfo>>() {
            });
            if(midApiResponse.getCode() == 200){
                return midApiResponse.getData();
            }
        }
        return null;
    }

    @Override
    public MidApiJsSdkInfo getJSSDK(MidApiGetJsSdkRequest request) {
        MidApiUtils.sign(request, midApiConfig.getAppKey(), midApiConfig.getAppSecret());
        log.info("请求MidApi获取jssdk：/oapi/js/sdk 入参{}", JSON.toJSONString(request));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(midApiConfig.getUrl() + "/oapi/js/sdk", request, String.class);
        log.info("请求MidApi获取jssdk：/oapi/js/sdk 出参{}", JSON.toJSONString(responseEntity));
        if(responseEntity.getStatusCode() == HttpStatus.OK){
            String body = responseEntity.getBody();
            MidApiResponse<MidApiJsSdkInfo> midApiResponse = JSON.parseObject(body, new TypeReference<MidApiResponse<MidApiJsSdkInfo>>() {
            });
            if(midApiResponse.getCode() == 200){
                return midApiResponse.getData();
            }
        }
        return null;
    }
}
